package com.example.qincetest.utils

import android.app.ActivityManager
import android.content.Context
import android.os.Debug

class MemoryMonitor(private val context: Context) {
    private val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    private val runtime = Runtime.getRuntime()

    // 获取应用内存信息
    fun getAppMemoryInfo(): AppMemoryInfo {
        val memInfo = Debug.MemoryInfo()
        Debug.getMemoryInfo(memInfo)

        return AppMemoryInfo(
            totalPss = memInfo.totalPss,            // 应用总PSS内存
            nativePss = memInfo.nativePss,          // 本地PSS内存
            dalvikPss = memInfo.dalvikPss,          // Dalvik PSS内存
            otherPss = memInfo.otherPss,            // 其他PSS内存
            heapAllocated = runtime.totalMemory(),   // 堆内存分配
            heapFree = runtime.freeMemory(),         // 堆内存空闲
            heapMax = runtime.maxMemory()            // 最大可用堆内存
        )
    }

    // 获取系统内存信息
    fun getSystemMemoryInfo(): SystemMemoryInfo {
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)

        return SystemMemoryInfo(
            availableMem = memoryInfo.availMem,
            totalMem = memoryInfo.totalMem,
            lowMemory = memoryInfo.lowMemory,
            threshold = memoryInfo.threshold
        )
    }

    data class AppMemoryInfo(
        val totalPss: Int,
        val nativePss: Int,
        val dalvikPss: Int,
        val otherPss: Int,
        val heapAllocated: Long,
        val heapFree: Long,
        val heapMax: Long
    ) {
        fun getHeapUsage() = ((heapAllocated - heapFree).toFloat() / heapMax * 100).toInt()
    }

    data class SystemMemoryInfo(
        val availableMem: Long,
        val totalMem: Long,
        val lowMemory: Boolean,
        val threshold: Long
    )
}